# !/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import sys
import re
from pylab import *
import numpy as np
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import shutil
from blepkg import *

# 2个allreport.txt 对比，针对单一距离的测试
def mkmkdownonedistmd(filepath,filepath2):
    
    str1 = filepath.split('/')[-1].split('.')[0].split('_')[-1]
    str2 = filepath2.split('/')[-1].split('.')[0].split('_')[-1]
    
    #print str1,str2
    
    fs = open(filepath,'rb')
    lines = fs.readlines()
    fs.close()
    fs2 = open(filepath2,'rb')
    lines2 = fs2.readlines()
    fs2.close()
    if os.path.split(sys.argv[sys.argv.index('-o') + 1])[0] == '':
        fo = open('BluetoothTestReport'+'_'+str1+'.md','wb')
    else:
        fo = open(os.path.split(sys.argv[sys.argv.index('-o') + 1])[0] + '/' + 'BluetoothTestReport'+'_'+str1+'.md','wb')
    
    fo.write("## Bluetooth Test Report\r\n")
    fo.write("序号 | 物理地址 | 发射功率(dB) | 测试距离(m) | 遮挡状况 | 平均信号强度 | 应收包数 | 实收包数 | 丢包率(%) " + str1 + " | 对比丢包率(%) " + str2 + "\r\n")
    fo.write("-------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- \r\n")
    pplk1 = 0
    pplk2 = 0
    rrrsi = 0
    count = 0
    nnor = 0
    aapc = 0
    aaaaa = {'mac':[],'plk1':[],'plk2':[]}
    for i in range(0,len(lines)):
        if lines[i][0] == '$':
            for j in range(0,len(lines2)):
                if lines[i].split()[lines[i].split().index('mac') + 1].lower() == lines2[j].split()[lines2[j].split().index('mac') + 1].lower():
                    count += 1
                    fo.write("%s | %s | %s | %s | %s | %s | %s | %s | %s | %s\r\n" % 
                            (count,
                             lines[i].split()[lines[i].split().index('mac') + 1],
                             lines[i].split()[lines[i].split().index('power') + 1],
                             lines[i].split()[lines[i].split().index('dist') + 1],
                             lines[i].split()[lines[i].split().index('occl') + 1],
                             lines[i].split()[lines[i].split().index('rssi') + 1],
                             lines[i].split()[lines[i].split().index('nor') + 1],
                             lines[i].split()[lines[i].split().index('apc') + 1],
                             lines[i].split()[lines[i].split().index('plk') + 1],
                             lines2[j].split()[lines2[j].split().index('plk') + 1]) )
                    rrrsi += float(lines[i].split()[lines[i].split().index('rssi') + 1])
                    nnor += float(lines[i].split()[lines[i].split().index('nor') + 1])
                    aapc += float(lines[i].split()[lines[i].split().index('apc') + 1])
                    pplk1 += float(lines[i].split()[lines[i].split().index('plk') + 1])
                    pplk2 += float(lines2[j].split()[lines2[j].split().index('plk') + 1])
                    aaaaa['mac'].append(lines[i].split()[lines[i].split().index('mac') + 1])
                    aaaaa['plk1'].append(lines[i].split()[lines[i].split().index('plk') + 1])
                    aaaaa['plk2'].append(lines2[j].split()[lines2[j].split().index('plk') + 1])
            
            #print "-w",lines[i].split()[lines[i].split().index('mac') + 1],"-s","10_00_no"        

    fo.write("%s | %s |   |   |  | %.2f | %.2f | %.2f | %.2f | %.2f\r\n" %(count+1,'平均数',rrrsi/count,nnor/count,aapc/count,pplk1/count,pplk2/count))
    fo.write("\r\n### %s 与 %s 每个设备丢包率的对比如下：\r\n" % (str1,str2))
    fo.write("------\r\n ![](image/data/%s)\r\n" % ('Contrast_' + str1 + '_' + str2 + '.jpg'))
    fo.write("### %s 接收到的所有设备接收数据状况如下\r\n" % (str1))
    for i in range(0,len(lines)):
        if lines[i][0] == '$':
            fo.write("##### %s 接收数据状况如下\r\n" % (lines[i].split()[lines[i].split().index('mac') + 1]))
            fo.write(" ![](image/data/%s_%s_%s_%s.jpg)\r\n" % ('_'.join(lines[i].split()[lines[i].split().index('mac') + 1].split(':')),lines[i].split()[lines[i].split().index('power') + 1],lines[i].split()[lines[i].split().index('dist') + 1],lines[i].split()[lines[i].split().index('occl') + 1]))
        

    fo.close()
    
    ax = plt.figure(num=1, figsize=(24, 12)).add_subplot(111)
    ax.set_title(str1 + '-' + str2 + ' device packet loss')
    # 设置y轴范围
    ylim(0,100)
    plt.xlabel('Device MAC')
    plt.ylabel('Packet Loss (%)')
    x = range(len(aaaaa['mac']))
    plt.grid(True)
    plt.plot(x, aaaaa['plk1'], 'bo-',label = str1)
    plt.plot(x, aaaaa['plk2'], 'ro-',label = str2)
    plt.xticks(x, aaaaa['mac'], rotation=45)
    plt.margins(0.08)
    plt.subplots_adjust(bottom=0.15)
    ax.legend(loc='upper right') 
    if os.path.split(sys.argv[sys.argv.index('-o') + 1])[0] == '':
        plt.savefig('Contrast_' + str1 + '_' + str2 + '.jpg')
    else:
        plt.savefig(os.path.split(sys.argv[sys.argv.index('-o') + 1])[0] + '/' + 'Contrast_' + str1 + '_' + str2 + '.jpg')
    #plt.show()
    #print aaaaa
    return

#单次多距离测试
def mkmkdownmanydistmd(filepath):
    if os.path.isfile(filepath):
        ff = os.path.dirname(filepath)
    elif os.path.isdir(filepath):
        ff = filepath

    if os.path.exists(ff + r"/BluetoothTestReport.md"):
        os.remove(ff + r"/BluetoothTestReport.md")
    fo = open(ff + r"/BluetoothTestReport.md","wb")

    alljpg = searchfile().search(ff + '/image' + '/data','^00_.*?jpg$')
    devicelist = []
    distlist = []
    jpgname = []
    for jpg in alljpg:
        jpgname.append(jpg.split('/')[-1])
        s = []
        s.append(jpg.split('/')[-1].split('.')[0][0:17].replace("_",":",5))
        s.append(jpg.split('/')[-1].split('.')[0].split('_')[-3])
        
        if s not in devicelist:
            devicelist.append(s)
        if int(jpg.split('/')[-1].split('.')[0].split('_')[-2]) not in distlist:
            distlist.append(int(jpg.split('/')[-1].split('.')[0].split('_')[-2]))
    
    distlist.sort()
    #print distlist 
    #print devicelist,len(devicelist)

    fo.write("![](image/logo/logo.jpg) ")
    fo.write("![](image/logo/bluetooth.jpg)\r\n\r\n")
    fo.write("[http://www.mtsports.com.cn](http://www.mtsports.com.cn)\r\n\r\n")
    fo.write("# MT Sports Football B Blurtooth Test Report\r\n\r\n")
    fo.write("---\r\n\r\n")
    fo.write("## 测试说明：\r\n\r\n")
    fo.write("## 设备、场地及佩戴说明：\r\n\r\n")
    fo.write("- **设备信息如下表：**\r\n\r\n")
    fo.write(" 序号 | 物理地址 | 发射功率(dB) | 板子型号 \r\n")
    fo.write(" --- | --- | --- | --- \r\n")
    for i in range(0,len(devicelist)):
        fo.write(" %s | %s | %s | %s \r\n" % (i+1,devicelist[i][0],devicelist[i][1],'-'))
    fo.write("\r\n- **设备如下图所示：**\r\n")
    fo.write("![](image/device/1.jpg) \r\n")
    fo.write("![](image/device/2.jpg) \r\n\r\n")
    fo.write("- **接收设备如下图所示：**\r\n")
    fo.write("![](image/device/3.jpg) \r\n\r\n")
    fo.write("- **无遮挡佩戴如下图：**\r\n")
    fo.write("![](image/device/4.jpg) \r\n\r\n")
    fo.write("- **半遮挡佩戴如下图：**\r\n")
    fo.write("![](image/device/5.jpg) \r\n\r\n")
    fo.write("- **全遮挡佩戴如下图：**\r\n")
    fo.write("![](image/device/6.jpg) \r\n\r\n")
    fo.write("---\r\n\r\n")
    fo.write("### 测试说明：\r\n\r\n")
    fo.write("- 设备测试从0m-100m(接收状况良好时会曾加距离),步进10m,分别测试无遮挡、半遮挡、全遮挡下的设备收包状况(丢包率)和信号状况。\r\n\r\n")
    fo.write("### 对比说明：\r\n\r\n ")
    fo.write("- 按发射功率、接收距离、遮挡情况分组比较丢包率和平均信号强度\r\n\r\n ")
    fo.write("_**以下图表没有曲线或曲线缺少的均是发生了至此往后没有收到据情况(设备异常或真实没收到数据)**_ \r\n")
    fo.write("_出现该图标_ ![](image/logo/error.jpg) _是缺失相应数据(没有捕捉到)导致没有生成对应图表_ \r\n\r\n")
    
    fo.write("#### 裸板0m距离，丢包率与信号强度曲线图\r\n")
    fo.write("![](image/data/Contrast_plk_init.jpg)\r\n")
    fo.write("![](image/data/Contrast_rssi_init.jpg)\r\n\r\n")
    
    xxx = [['plk','丢包率'],['rssi','信号强度']]
    occl = [['no','无遮挡'],['half','半遮挡'],['all','全遮挡']]
    for i in range(0,len(xxx)):
        for j in range(0,len(occl)):
            filename = ff + '/Contrast_' + xxx[i][0] + '_' + occl[j][0] + '.md'
            if os.path.exists(filename):
                #print filename
                fs = open(filename,'rb')
                lines = fs.readlines()
                fs.close()
                os.remove(filename)
                fo.write("####  装壳，%s,%s与距离关系表格和曲线图\r\n" % (occl[j][1],xxx[i][1]))
                for k in range(0,len(lines)):
                    fo.write(lines[k])
                fo.write("\r\n")
                fo.write("![](image/data/Contrast_%s_%s.jpg)\r\n\r\n" % (xxx[i][0],occl[j][0]))

    fo.write("## 单个设备的丢包状况及信号情况在固定距离时情况如下：\r\n\r\n")
    for i in range(0,len(distlist)):
        for j in range(0,len(devicelist)):
            for k in range(len(occl)):
                filename = ff + '/image/data/' + devicelist[j][0].replace(":","_",5) + '_' + devicelist[j][1] + '_' + str(distlist[i]) + '_'  +occl[k][0] + '.jpg'
                if os.path.exists(filename):
                    fo.write("#### %s,%sm,%s\r\n" % (devicelist[j][0],str(distlist[i]),occl[k][1]))
                    fo.write("![](image/data/%s.jpg)\r\n\r\n" % (devicelist[j][0].replace(":","_",5) + '_' + devicelist[j][1] + '_' + str(distlist[i]) + '_'  +occl[k][0]))
    fo.close()
    
    return
    
#单次多距离测试的表格 行，列，值
#  列
# | | | | 行
# | | 值 | |
# | | | |
def mkmdtable(line,row,val,filepath,title):
    fo = open(filepath,'wb')
    fo.write("\r\n## %s\r\n" % (title))
    if len(row) > 0:
        fo.write(" %s |" % '-')
        for i in range(0,len(row) - 1):        
            fo.write(" %s |" % (row[i]))
        fo.write(" %s \r\n" % (row[-1]))
        for i in range(0,len(row)):        
            fo.write(" -------- |")
        fo.write(" -------- \r\n")
    if len(line) > 0 and len(line) == len(val):
        for i in range(0,len(line)):
            fo.write(" %s |" % (line[i]))
            for j in range(0,len(val[i]) - 1):
                fo.write(" %s |" % (val[i][j]))
            fo.write(" %s \r\n" % (val[i][-1]))
    fo.write("\r\n")              
    fo.close()
    return    

#./image/data
#./image/device
#./image/logo
#./olddata
def mkdir(savepath):
    ff = os.path.dirname(savepath)
    if not os.path.exists(ff + r'/image'):
        os.makedirs(ff + r'/image')
    if not os.path.exists(ff + r'/image/data'):
        os.makedirs(ff + r'/image/data')
    if not os.path.exists(ff + r'/image/device'):
        os.makedirs(ff + r'/image/device')
    if not os.path.exists(ff + r'/image/logo'):
        os.makedirs(ff + r'/image/logo')  
    if not os.path.exists(ff + r'/olddata'):
        os.makedirs(ff + r'/olddata') 
    return

def mkmkdownreadme(savepath,jumplist):
    if os.path.isfile(savepath):
        ff = os.path.dirname(savepath)
    elif os.path.isdir(savepath):
        ff = savepath
    #print ff
    if os.path.exists(ff + r"/README.md"):
        os.remove(ff + r"/README.md")
    fo = open(ff + r"/README.md","wb")

    fo.write("![](image/logo/logo.jpg)\r\n")
    fo.write("[http://www.mtsports.com.cn](http://www.mtsports.com.cn)\r\n")
    fo.write("# MT Sports Football B Blurtooth Test Report\r\n")
    fo.write("---\r\n")
    fo.write("**一些说明：**\r\n")
    fo.write(" * 原始数据文件命名，物理地址以下划线分割.txt ,如：00\_0b\_57\_1d\_38\_e1.txt\r\n")
    fo.write(" * 单个设备的丢包状况及信号状况图表命名： 物理地址以下划线分割\_发射功率\_测试距离\_遮挡状况.jpg\r\n")
    fo.write(" * 多个设备的丢包状况对比图表命名： Contrast\_plk\_遮挡状况\_发射功率.jpg\r\n")
    fo.write(" * 多个设备的信号状况对比图表命名： Contrast\_rssi\_遮挡状况\_发射功率.jpg\r\n")
    for i in range(0,len(jumplist)):
        fo.write("\r\n### _[查看%s详细测试报告](%s)_\r\n" % (jumplist[i].split('.')[0].split('_')[-1],jumplist[i]))
    fo.close()
    return

#批量复制文件
def cpfile(srcPath,destPath,mc):

    for f in os.listdir(srcPath):
        f = os.path.join(srcPath,f) 
        if os.path.isfile(f) and re.match(mc,os.path.basename(f)):
            if os.path.abspath(srcPath) != os.path.abspath(destPath):
                shutil.copy(f,destPath)
        elif os.path.isdir(f):           
            cpfile(f,destPath,mc)
    return 

#批量移动文件    
def mvfile(srcPath,destPath,mc):

    for f in os.listdir(srcPath):
        f = os.path.join(srcPath,f) 
        if os.path.isfile(f) and re.match(mc,os.path.basename(f)):
            if os.path.abspath(srcPath) != os.path.abspath(destPath):
                shutil.copy(f,destPath)
                os.remove(f)
            elif os.path.isdir(f):           
                mvfile(f,destPath,mc)
    return 
    

if __name__ == '__main__':
    
    if '-o' in sys.argv:
        str1 = sys.argv[sys.argv.index('-o') + 1].split('/')[-1].split('.')[0].split('_')[-1]
        str2 = sys.argv[sys.argv.index('-o') + 2].split('/')[-1].split('.')[0].split('_')[-1]
        ss = ['BluetoothTestReport_'+str1+'.md','BluetoothTestReport_'+str2+'.md']
        ff = os.path.dirname(sys.argv[sys.argv.index('-o') + 1])#当前目录
        ffp = os.path.dirname(os.path.join(os.path.dirname(ff),os.path.pardir))#上级目录
        
        mkdir(sys.argv[sys.argv.index('-o') + 1])  
             
        mkmkdownonedistmd(sys.argv[sys.argv.index('-o') + 1],sys.argv[sys.argv.index('-o') + 2]) 
        
        mkmkdownreadme(sys.argv[sys.argv.index('-o') + 1],ss)  
        
        
        mvfile(ff,ff+"/image/data/",'^.*?jpg$')
        mvfile(ff,ff+"/olddata/",'^.*?txt$')   
        cpfile(ffp,ff+"/image/data/",'^.*?jpg$') 
        cpfile(ffp,ff+"/olddata/",'^.*?txt$')   
        cpfile('../device/',ff+"/image/device/",'^.*?jpg$')
        cpfile('../logo/',ff+"/image/logo/",'^.*?jpg$') 
        
        
    elif '-m' in sys.argv:
        ss = ['BluetoothTestReport.md']
        ff = os.path.dirname(sys.argv[sys.argv.index('-m') + 1])#当前目录
        ffp = os.path.dirname(os.path.join(os.path.dirname(ff),os.path.pardir))#上级目录
        
        mkdir(sys.argv[sys.argv.index('-m') + 1])
        cpfile(ffp,ff+"/image/data/",'^.*?jpg$') 
        mkmkdownmanydistmd(sys.argv[sys.argv.index('-m') + 1])       
        mkmkdownreadme(sys.argv[sys.argv.index('-m') + 1],ss) 
        
        mvfile(ff,ff+"/olddata/",'^.*?txt$')   
        mvfile(ff,ff+"/image/data/",'^.*?jpg$')
        cpfile('../device/',ff+"/image/device/",'^.*?jpg$')
        cpfile('../logo/',ff+"/image/logo/",'^.*?jpg$') 

        #cpfile(ffp,ff+"/olddata/",'^.*?txt$') 
        
    print 'over'


